﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using Shared.Model;
using Client;
using ManageSystem.Dialog;

namespace ManageSystem.Manager
{
    public partial class FormProduct : UserControl
    {
        //需要的初始化的数据

        public FormProduct()
        {
            InitializeComponent();
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            Clear();
            //获取MAC地址

            string productMac = this.textBoxMacAddr.Text.Trim();
            string productSn = this.textBoxProductSn.Text.Trim();
            string bosaSn = this.textBoxBosaSn.Text.Trim();

            if (string.IsNullOrEmpty(productMac)&&string.IsNullOrEmpty(productSn)&&string.IsNullOrEmpty(bosaSn))
            {
                MessageBox.Show("MAC地址、BOSA_SN和SN号码为空");
                ClearMac();
                return ;
            }

            //添加一个获取产品数据和过程数据的方法在此处
            Task.Factory.StartNew(()=>
            {
                ShowProductAndProcess(productMac,productSn,bosaSn);
            });
        }

        //根据MAC获取PRODUCT和PROCESS的信息
        private void ShowProductAndProcess(string mac,string sn,string bosa)
        {
            //获取相应的PRODUCT信息和PROCESS信息
            PRODUCT productW = new PRODUCT();
            productW.SetWhere();
            if (string.IsNullOrEmpty(mac) == false)
            {
                //productW.MAC = mac;
                productW.SetWhere(string.Format("(MAC='{0}' OR YCD_MAC='{0}')", mac));
            }
            else if (string.IsNullOrEmpty(sn) == false)
            {
                productW.SetWhere(string.Format("MAC=(select MACAddr from Modem.dbo.Device_Data where SN='{0}')", sn));
            }else if (string.IsNullOrEmpty(bosa) == false)
            {
                productW.SetWhere(string.Format("YCD_MAC=(SELECT YCD_MAC FROM Modem.dbo.YCD_DEVICE WHERE LIGHT_MODULE_SN='{0}')",bosa));
            }

            var selectProduct = MethodWcf.SelectProductClient(productW);
            if (selectProduct.result==false)
            {
                MessageBox.Show(string.Format("未能找到产品数据，错误信息为：{0}", selectProduct.message));
                ClearMac();
                return;
            }

            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();
            deviceW.MACAddr = selectProduct.value[0].MAC;
            var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);

            if (selectDevice.result)
            {
                //展示产品信息到界面上
                ShowProductMsg(selectProduct.value[0], selectDevice.value[0]);
            }
            else
            {
                ShowProductMsg(selectProduct.value[0], null);
            }

            //PROCESS按照倒叙排序
            PROCESS processW = new PROCESS();
            //processW.SetWhere();
            //processW.MAC = selectProduct.value[0].MAC;
            processW.SetWhere(string.Format("(MAC='{0}' OR MAC='{1}')",selectProduct.value[0].MAC,selectProduct.value[0].YCD_MAC));

            var selectProcess = MethodWcf.SelectProcessClient(processW);
            if (selectProduct.result)
            {
                //展示过程信息到界面上
                var listProcess = (from p in selectProcess.value
                                   orderby p.ID descending
                                   select p).ToList();

                ShowProcessMsg(listProcess);
            }
        }

        //展示过程信息
        private void ShowProcessMsg(List<PROCESS> listProcess)
        {
            //throw new NotImplementedException();
            for(int i = 0; i < listProcess.Count; i++)
            {
                ShowProcessOne(listProcess[i]);
            }
        }

        //展示一条信息
        private void ShowProcessOne(PROCESS process)
        {
            if (process == null) return;
            if (this.listViewProcess.InvokeRequired)
            {
                Action<PROCESS> a = new Action<PROCESS>(ShowProcessOne);
                Invoke(a, process);
            }
            else
            {
                ListViewItem item = new ListViewItem();
                item.Text = process.ID.ToString();

                if (process.WORKER_ID != null)
                    item.SubItems.Add(process.STATION_ID.ToString());
                else
                    item.SubItems.Add("");

                item.SubItems.Add(process.WORKER_NAME);

                if (process.LINE_ID != null)
                    item.SubItems.Add(process.LINE_ID.ToString());
                else
                    item.SubItems.Add("");

                if (process.NODE_ID != null)
                    item.SubItems.Add(process.NODE_ID.ToString());
                else
                    item.SubItems.Add("");

                item.SubItems.Add(process.TEST_RESULT);

                if (process.START_TIME != null)
                    item.SubItems.Add(process.START_TIME.ToString());
                else
                    item.SubItems.Add("");

                if (process.END_TIME != null)
                    item.SubItems.Add(process.END_TIME.ToString());
                else
                    item.SubItems.Add("");

                this.listViewProcess.Items.Add(item);
            }
        }

        /// <summary>
        /// 展示产品信息
        /// </summary>
        /// <param name="pRODUCT"></param>
        private void ShowProductMsg(PRODUCT product,Device_Data device)
        {
            if (this.InvokeRequired)
            {
                Action<PRODUCT,Device_Data> d = new Action<PRODUCT,Device_Data>(ShowProductMsg);
                this.Invoke(d, product,device);
            }
            else
            {
                if (device != null)
                {
                    this.textBoxSn.Text = device.SN;
                    this.textBoxType.Text = device.DeviceType;
                    this.textBoxIdentify.Text = device.DeviceSerialNumber;
                    this.textBoxCode.Text = device.ProductCode;
                    this.textBoxProvince.Text = device.HW_PROVINCE_NAME;
                }

                if (product != null)
                {
                    this.textBoxYcdMac.Text = product.YCD_MAC;
                    this.textBoxProductMac.Text = product.MAC;
                    this.textBoxLineId.Text = product.LINE_ID.ToString();
                    this.textBoxNodeId.Text = product.NODE_ID.ToString();
                    this.textBoxTestResult.Text = product.TEST_RESULT;
                    this.textBoxStartTime.Text = product.START_TIME.ToString();
                    this.textBoxEndTime.Text = product.END_TIME.ToString();
                }

            }
        }

        private void Clear()
        {
            ClearLogView();
            ClearProductView();
            ClearListView(this.listViewProcess);
        }

        //清空过程信息表
        private void ClearListView(ListView view)
        {
            view.Items.Clear();
        }

        //清空日志显示窗口
        private void ClearLogView()
        {
            this.textBoxTestName.Clear();
            this.textBoxTestResultLog.Clear();
            this.richTextBoxLogShow.Clear();
        }

        //清空产品状态信息窗口
        private void ClearProductView()
        {
            this.textBoxSn.Clear();
            this.textBoxType.Clear();
            this.textBoxIdentify.Clear();
            this.textBoxCode.Clear();
            this.textBoxProvince.Clear();
            this.textBoxProductMac.Clear();
            this.textBoxYcdMac.Clear();
            this.textBoxLineId.Clear();
            this.textBoxNodeId.Clear();
            this.textBoxTestResult.Clear();
            this.textBoxStartTime.Clear();
            this.textBoxEndTime.Clear();
        }

        //清空MAC和工序ID
        private void ClearMac()
        {
            if (InvokeRequired)
            {
                Action d = new Action(ClearMac);
                Invoke(d);
            }
            else
            {
                this.textBoxMacAddr.Clear();
                this.textBoxProductSn.Clear();
                this.textBoxBosaSn.Clear();
                //this.textBoxChoiceNode.Clear();
                this.textBoxMacAddr.Focus();
            }
        }

        private void listViewProcess_MouseClick(object sender, MouseEventArgs e)
        {
            //查询PROCESS对应的产品LOG信息
            ClearLogView();
            //获取选择的PROCESSID
            if (listViewProcess.Items.Count == 0 || listViewProcess.SelectedItems.Count == 0) return;
            //查找相应的LOG信息
            long processId;
            if (long.TryParse(listViewProcess.SelectedItems[0].Text, out processId))
            {
                Task.Factory.StartNew(()=>
                {
                    GetLogMsg(processId);
                });
            }
        }
        //查找相应的LOG信息
        private void GetLogMsg(long processId)
        {
            TEST_TOP topW = new TEST_TOP();
            topW.SetWhere();

            topW.PROCESS_ID = processId;

            var selectTop = MethodWcf.SelectTestTopClient(topW);

            if (selectTop.result)
            {
                ShowLogMsg(selectTop.value[0]);
            }
        }
        //展示LOG信息
        private void ShowLogMsg(TEST_TOP log)
        {
            if (InvokeRequired)
            {
                Action<TEST_TOP> d = new Action<TEST_TOP>(ShowLogMsg);
                Invoke(d, log);
            }
            else
            {
                this.textBoxTestName.Text = log.PROJECT;
                this.textBoxTestResultLog.Text = log.RESULT;
                this.richTextBoxLogShow.Text = log.CONTEXT;
            }
        }

        //private void textBoxChoiceNode_Enter(object sender, EventArgs e)
        //{
        //    DialogNode node = new DialogNode(this.textBoxChoiceNode, null);
        //    node?.ShowDialog();
        //}

        //private void buttonChange_Click(object sender, EventArgs e)
        //{
        //    //获得MAC地址
        //    string productMac = this.textBoxMacAddr.Text.Trim();

        //    if (string.IsNullOrEmpty(productMac))
        //    {
        //        MessageBox.Show("MAC地址为空");
        //        ClearMac();
        //        return;
        //    }

        //    //判断MAC地址是否12位
        //    if (productMac.Length != 12)
        //    {
        //        MessageBox.Show("MAC地址不为12位，请检查MAC地址");
        //        ClearMac();
        //        return;
        //    }
        //    //获取需要修改到的NODE_ID名称

        //    long nodeId;
        //    if(long.TryParse(this.textBoxChoiceNode.Text,out nodeId) == false)
        //    {
        //        MessageBox.Show("未选择需要修改到的工序");
        //        ClearMac();
        //        return;
        //    }
        //    //设置更新条件

        //    PRODUCT proU = new PRODUCT();
        //    proU.SetWhere();

        //    proU.MAC = productMac;
        //    //proU.TEST_RESULT = "N";

        //    proU.SetUpdate();
        //    proU.NODE_ID = nodeId;

        //    var updateProduct = MethodWcf.UpdateProductClient(proU);
        //    if (updateProduct.result)
        //    {
        //        MessageBox.Show("修改工序成功");
        //    }
        //    else
        //    {
        //        MessageBox.Show("修改工序失败");
        //        ClearMac();
        //    }        
        //}
    }
}
